package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author wangqian
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //Todo 合并完成以后，要对采购单状态进行检查
        Long finalPurchaseId = purchaseId;
        List<Long> list = mergeVo.getItems();
        List<PurchaseDetailEntity> collects = list.stream().map(i->{
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setPurchaseId(finalPurchaseId);
            detail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detail;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collects);
    }

    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或已分配状态
        List<PurchaseEntity> changePurchase = ids.stream().map(id->{
           PurchaseEntity byId = this.getById(id);
           return byId;
        }).filter(item->{
            if(item.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()||
                    item.getStatus() ==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                return true;
            }
            return false;
        }).map(item->{
            //筛选完以后，实时更改采购单状态
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单的采购状态
        this.updateBatchById(changePurchase);
        //3、改变采购项的状态
        changePurchase.forEach(item->{
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> changedEntities = detailEntities.stream().map(entity->{
                PurchaseDetailEntity changedEntity = new PurchaseDetailEntity();
                changedEntity.setId(entity.getId());
                changedEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return changedEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(changedEntities);
        });
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        //1、改变采购单状态
        Long id = purchaseDoneVo.getId();
        //2、改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> doneVos = purchaseDoneVo.getItems();

        List<PurchaseDetailEntity> needChangeStatus = new ArrayList<>();
        for(PurchaseItemDoneVo item:doneVos){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            //todo 采购失败，添加失败原因
            //应采购多少，实际采购多少
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());

            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //需要进行入库操作

                //查询采购入库项

                PurchaseDetailEntity detailEntityForItem = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntityForItem.getSkuId(),detailEntityForItem.getWareId(),detailEntityForItem.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            needChangeStatus.add(detailEntity);
        }
        //采购项状态更新完成
        purchaseDetailService.updateBatchById(needChangeStatus);


        //更改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode(): WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        //3、将成功采购的进行入库

    }

}